<template>
  <div class="container mx-auto max-w-screen-xl mt-5">
    <el-card class="detail" :style="{ backgroundImage: `url(${communityDetail?.detail?.cover})` }">
      <el-col class="header">
        <el-page-header icon="" title="">
          <template #icon>
            <el-icon color="#666" :size="20" @click="$router.go(-1)"> <Back /></el-icon>
          </template>
          <template #title>
            <span class="text">返回</span>
          </template>
          <template #content>
            <div class="flex items-center">
              <span class="text-large font-800 mr-3 animate__animated animate__bounce name text">{{ communityDetail?.detail?.title }}</span>
              <el-tag>{{ communityDetail?.detail?.viewNum || communityDetail?.detail?.views }} 浏览</el-tag>
            </div>
          </template>

          <el-descriptions :column="3" class="mt-4">
            <el-descriptions-item label="标题" class="color-white"
              ><el-tag>{{ communityDetail?.detail?.title }}</el-tag></el-descriptions-item
            >
            <el-descriptions-item label="🔖类型">
              <el-tag>{{ communityDetail?.detail?.aboutInfo?.category?.name || communityDetail?.detail?.category?.name }}</el-tag></el-descriptions-item
            >
            <el-descriptions-item label="🔥热度"
              ><el-tag>{{ communityDetail?.detail?.likeNum || communityDetail?.detail?.likes }}</el-tag></el-descriptions-item
            >
            <el-descriptions-item label="发布时间">
              <el-tag>{{ formatDate(communityDetail?.detail?.createTime || communityDetail?.detail?.createdAt) }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="作者">
              <el-tag>{{ (communityDetail as any)?.detail?.aboutInfo?.author || (communityDetail as any)?.detail?.author?.nickname }}</el-tag></el-descriptions-item
            >
          </el-descriptions>
          <p class="mt-4 text-sm text">{{ communityDetail?.detail?.desc || communityDetail?.detail?.description }}</p>
        </el-page-header>
        <el-col>
          <el-divider />
        </el-col>
      </el-col>
    </el-card>

    <!-- 内容区域 -->
    <el-card class="mt-5" v-if="communityDetail">
      <div class="content" v-html="communityDetail.detail.content"></div>
    </el-card>

    <!-- 评论区域 -->
    <el-card class="mt-5">
      <CommentSection
        :article-id="route.query.id as string"
        :comments="comments"
        :total="commentPageData.total"
        :page-size="commentPageData.pageSize"
        :current-page="commentPageData.page"
        :loading="commentLoading"
        :submitting="commentSubmitting"
        :show-location-select="true"
        :can-delete="false"
        @submit="handleCommentSubmit"
        @like="handleCommentLike"
        @like-reply="handleReplyLike"
        @page-change="changeCommentPage"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
// 使用真实API接口
import { getCommunityDetailAPI, likeCommunityAPI } from "@/api/web/community"
import { getArticleCommentsAPI, publishArticleCommentAPI } from "@/api/web/comment"
// import { getMockCommunityDetail, getMockComments } from "./mockData"
import { onMounted, ref } from "vue"
import { useRoute } from "vue-router"
import { ElMessage } from 'element-plus'
import type { CommunityItem, CommentItem } from "@/types/web/community"
import CommentSection from "@/components/CommentSection/UniversalComment.vue"

// 页面路由
const route = useRoute()

// 社区内容详情
const communityDetail = ref<{ detail: CommunityItem }>()

// 获取详情信息
const getCommunityDetail = async () => {
  try {
    const res = await getCommunityDetailAPI(route.query.id as string)
    if (res.data) {
      // 按照文章详情页面的数据结构，包装为 { detail: data } 格式
      communityDetail.value = { detail: res.data } as any
    }
  } catch (error) {
    ElMessage.error('获取社区详情失败')
    console.error('获取社区详情失败:', error)
  }
}

// 评论列表
const comments = ref<CommentItem[]>([])

// 评论加载状态
const commentLoading = ref(false)

// 评论提交状态
const commentSubmitting = ref(false)

// 评论分页数据
const commentPageData = ref({
  page: 1,
  pageSize: 10,
  total: 0
})

// 获取评论列表
const getCommunityComments = async () => {
  commentLoading.value = true
  try {
    // 使用新的公开评论接口，无需用户名
    const res = await getArticleCommentsAPI(
      route.query.id as string,
      commentPageData.value.page,
      commentPageData.value.pageSize
    )
    if (res.data) {
      comments.value = (res as any).data || []
      commentPageData.value.total = (res as any).total || 0
    }
  } catch (error) {
    ElMessage.error('获取评论列表失败')
    console.error('获取评论列表失败:', error)
  } finally {
    commentLoading.value = false
  }
}

// 切换评论分页
const changeCommentPage = (page: number) => {
  commentPageData.value.page = page
  getCommunityComments()
}

// 提交评论
const handleCommentSubmit = async (data: any) => {
  commentSubmitting.value = true
  try {
    // 使用新的公开评论接口，无需用户名
    const res = await publishArticleCommentAPI(
      route.query.id as string,
      {
        nickname: data.nickname,
        content: data.content,
        address: data.location || data.address,
        time: new Date().toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        }).replace(/\//g, '-')
      }
    )
    if (res.data) {
      ElMessage.success(data.parentId ? '回复成功！' : '评论成功！')
      // 刷新评论列表
      getCommunityComments()
    }
  } catch (error) {
    ElMessage.error('评论提交失败')
    console.error('评论提交失败:', error)
  } finally {
    commentSubmitting.value = false
  }
}

// 点赞评论
const handleCommentLike = async (commentId: string) => {
  try {
    // 这里需要调用评论点赞API，暂时使用帖子点赞API
    const res = await likeCommunityAPI(commentId)
    if ((res as any).code === 200) {
      ElMessage.success('点赞成功！')
      // 更新本地数据
      const comment = comments.value.find((c: CommentItem) => c._id === commentId)
      if (comment) {
        comment.likes = (res as any).data.likes
        comment.isLiked = (res as any).data.isLiked
      }
    }
  } catch (error) {
    ElMessage.error('点赞失败')
    console.error('点赞失败:', error)
  }
}

// 点赞回复
const handleReplyLike = async (replyId: string) => {
  try {
    // 这里需要调用回复点赞API，暂时使用帖子点赞API
    const res = await likeCommunityAPI(replyId)
    if ((res as any).code === 200) {
      ElMessage.success('点赞成功！')
      // 更新本地数据
      comments.value.forEach((comment: CommentItem) => {
        const reply = comment.replies?.find((r: any) => r._id === replyId)
        if (reply) {
          reply.likes = (res as any).data.likes
          reply.isLiked = (res as any).data.isLiked
        }
      })
    }
  } catch (error) {
    ElMessage.error('点赞失败')
    console.error('点赞失败:', error)
  }
}

// 格式化日期
const formatDate = (date?: string) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN')
}

onMounted(() => {
  getCommunityDetail()
  getCommunityComments()
})
</script>

<style lang="scss" scoped>
.detail {
  background-size: cover;
  background-repeat: no-repeat;
  min-height: 300px;
  color: #fff !important;
}
::v-deep(.el-descriptions__body) {
  background: transparent;
}
.name {
  font-size: 20px;
}
.header {
  height: 100%;
  display: flex;
  justify-content: space-between;
  flex-direction: column;
  min-height: 300px;
}
.text {
  text-shadow: 0 0 6px #000;
  color: #fff;
}
::v-deep(.el-descriptions__label:not(.is-bordered-label)) {
  text-shadow: 0 0 6px #000;
  color: #fff;
}

.content {
  padding: 20px;
  line-height: 1.8;
  font-size: 16px;
}
</style>

